﻿using mozhi.smarterp.BasicData.Enums;
using mozhi.smarterp.BasicData.Products.Repositories;
using mozhi.smarterp.BasicData.Units;
using NPOI.Util;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;
using Volo.Abp.Guids;

namespace mozhi.smarterp.BasicData.Products.Services
{
    public class ProductAuxiliaryUnitManager : DomainService
    {
        private IProductAuxiliaryUnitRepository _repository;

        private IGuidGenerator _guidGenerator;

        private IProductRepository _productRepository;

        private IUnitRepository _unitRepository;

        public ProductAuxiliaryUnitManager(IProductAuxiliaryUnitRepository repository, IGuidGenerator guidGenerator, IProductRepository productRepository , IUnitRepository unitRepository)
        {
            _repository = repository;
            _guidGenerator = guidGenerator;
            _productRepository = productRepository;
            _unitRepository = unitRepository;
        }

        public async Task<ProductAuxiliaryUnit> GetAsync(Guid? id, Guid productId, AuxiliaryUnitRateType type, Guid otherUnitId, decimal conversionRate , bool activated)
        {
            ProductAuxiliaryUnit auxiliaryUnit;

            var product = await _productRepository.GetAsync(productId);

            if (product == null)
                throw new UserFriendlyException($"产品：{id}不存在", "100000");

            var otherUnit = await _unitRepository.GetAsync(otherUnitId);

            if (otherUnit == null)
                throw new UserFriendlyException($"其他单位：{otherUnitId}不存在", "100000");

            if (!otherUnit.Activated)
                throw new UserFriendlyException($"其他单位：{otherUnit.Name}已禁用", "100000");

            var matchCount = await _repository.GetCountAsync(productId, otherUnitId, id);

            if (matchCount > 0)
                throw new UserFriendlyException($"产品：{product.Code}的辅助单位：{otherUnit.Name}换算已存在", "100000");

            if (id.HasValue)
            {
                auxiliaryUnit = await _repository.GetAsync(id.Value);

                if (auxiliaryUnit == null)
                    throw new UserFriendlyException($"产品单位换算：{id}不存在", "100000");

                if (productId != auxiliaryUnit.ProductId)
                    throw new UserFriendlyException($"产品单位换算不允许更改产品", "100000");

                auxiliaryUnit.Change(type, otherUnitId, conversionRate , activated);
            }
            else
                auxiliaryUnit = new ProductAuxiliaryUnit(_guidGenerator.Create(), product.Id, type, product.BasicUnitId, otherUnitId, conversionRate , activated);

            return auxiliaryUnit;
        }
    }
}
